Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution: defflatten(self, root: TreeNode) ->None: """ Do not return anything, modify root in-place instead. """ifnotroot: returnNonestack= [root] prev=TreeNode(left=root) whilestack: curr=stack.pop() prev.left=Noneprev.right=currifcurr.right: stack.append(curr.right) ifcurr.left: stack.append(curr.left) prev=curr
# Definition for a binary tree node.# class TreeNode# attr_accessor :val, :left, :right# def initialize(val = 0, left = nil, right = nil)# @val = val# @left = left# @right = right# end# end# @param {TreeNode} root# @return {Void} Do not return anything, modify root in-place instead.defflatten(root)returnnilifroot.nil?stack=[root]prev=TreeNode.new(left=root)while not stack.empty?curr=stack.popprev.left=nilprev.right=currstack.push(curr.right)if not curr.right.nil?stack.push(curr.left)if not curr.left.nil?prev=currendend